package com.xavi.socketdecodemjpeg

import android.os.Build
import android.os.Bundle
import android.os.StrictMode
import android.os.StrictMode.ThreadPolicy
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.dwy.decodemjpeg.MjpegDecoderManager
import com.dwy.decodemjpeg.ObjectUtil
import java.io.File
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Socket

class MainActivity : AppCompatActivity() {
    private var ivPic: ImageView? = null
    private var tv_tips: TextView? = null
    private var btn_play: ImageButton? = null
    private var pixelType = 0
    private var tvPixel1: TextView? = null
    private var tvPixel2: TextView? = null
    private var tvPixel3: TextView? = null
    private var tvPixel4: TextView? = null
    private var tvPixel5: TextView? = null
    private var tvRecordVideo: TextView? = null
    private var tvRotate0: TextView? = null
    private var tvRotate90: TextView? = null
    private var tvRotate180: TextView? = null
    private var tvRotate270: TextView? = null
    private var tvPixelList = arrayListOf<TextView?>()
    private var tvDegreeList = arrayListOf<TextView?>()
    private var isPlay = false
    private var state = false
    private var socket: Socket? = null
    private val ip = "192.168.10.1"
    private val port = 7130
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
    }

    private fun initView() {
        //TestConfig.ifServerSendData = true
        //TestConfig.enableSourceDataRestore = true
        //TestConfig.enableVideoDataRestore = true
        //强制允许在主线程操作网络访问
        if (Build.VERSION.SDK_INT > 9) {
            StrictMode.setThreadPolicy(ThreadPolicy.Builder().permitAll().build())
        }
        ivPic = findViewById(R.id.ivPic)
        tv_tips = findViewById(R.id.tv_tips)
        tv_tips?.text = "未连接"
        tvPixel1 = findViewById(R.id.tvPixel1)
        tvPixel2 = findViewById(R.id.tvPixel2)
        tvPixel3 = findViewById(R.id.tvPixel3)
        tvPixel4 = findViewById(R.id.tvPixel4)
        tvPixel5 = findViewById(R.id.tvPixel5)
        tvRotate0 = findViewById(R.id.tvRotate0)
        tvRotate90 = findViewById(R.id.tvRotate90)
        tvRotate180 = findViewById(R.id.tvRotate180)
        tvRotate270 = findViewById(R.id.tvRotate270)
        tvRecordVideo = findViewById(R.id.tvRecordVideo)
        tvPixelList.addAll(listOf(tvPixel1, tvPixel2, tvPixel3, tvPixel4, tvPixel5))
        tvPixelList.forEach { tv ->
            tv?.setOnClickListener {
                selectPixelTv(tv)
                MjpegDecoderManager.stopVideoPlay(pixelType)
                startPlay(true)
            }
        }
        selectPixelTv(tvPixel1)

        tvDegreeList.addAll(listOf(tvRotate0, tvRotate90, tvRotate180, tvRotate270))
        tvDegreeList.forEach { tv ->
            tv?.setOnClickListener {
                selectDegreeTv(tv)
            }
        }
        selectDegreeTv(tvRotate0)

        tvRecordVideo?.tag = "0"
        var videoFile = File("")
        tvRecordVideo?.setOnClickListener {
            if (tvRecordVideo?.tag == "0") {
                tvRecordVideo?.tag = "1"
                tvRecordVideo?.text = "正在录视频,点击可停止"
                videoFile = MjpegDecoderManager.startRecordVideo(this)
            } else {
                tvRecordVideo?.tag = "0"
                tvRecordVideo?.text = "开始录视频"
                MjpegDecoderManager.stopRecordVideo()
                Toast.makeText(this, "视频文件路径:${videoFile.absolutePath}", Toast.LENGTH_SHORT).show()
            }
        }

        btn_play = findViewById(R.id.btn_play)
        btn_play?.setOnClickListener(View.OnClickListener {
            if (isPlay) {
                stopPlay(true)
            } else {
                startPlay(true)
            }
        })

        findViewById<Button>(R.id.btnSendHex).setOnClickListener {
            if (!state || socket == null) {
                Toast.makeText(this, "未连接", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val hex = findViewById<EditText>(R.id.etHex).text.toString().replace(" ", "")
            if (TextUtils.isEmpty(hex) || hex.length % 2 != 0) {
                Toast.makeText(this, "请输入完整的16进制数据", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (sendMsg(socket!!, ObjectUtil.parseHexStringToBytes(hex))) {
                Toast.makeText(this, "发送成功", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "发送失败", Toast.LENGTH_SHORT).show()
            }
        }

        findViewById<Button>(R.id.btnClearHex).setOnClickListener {
            findViewById<EditText>(R.id.etHex).setText("")
        }
    }

    override fun onPause() {
        super.onPause()
        stopPlay(false)
    }

    override fun onResume() {
        super.onResume()
        startPlay(true)
    }

    override fun onDestroy() {
        super.onDestroy()
        MjpegDecoderManager.destory()
    }

    private fun startPlay(showFailTips: Boolean) {
        if (MjpegDecoderManager.connectCamera() && MjpegDecoderManager.configVideoFormat() && MjpegDecoderManager.openCamera(pixelType)) {
            state = false
            //socket.sendUrgentData(89)
            //MjpegDecoderManager.configRotationDegree(90f)
            MjpegDecoderManager.startVideoPlay(ivPic!!, {
                runOnUiThread {
                    btn_play!!.setImageResource(R.drawable.ic_pause)
                    tv_tips!!.text = "正在播放"
                    tv_tips!!.postDelayed({ tv_tips!!.text = "" }, 2000)
                    isPlay = true
                }
                Thread {
                    try {
                        socket = Socket()
                        socket?.connect(InetSocketAddress(ip, port), 6000)
                        state = true
                    } catch (e: Exception) {
                        e.printStackTrace()
                        state = false
                    }
                }.start()
                null
            }) { throwable: Throwable? ->
                if (!showFailTips) return@startVideoPlay
                if (throwable != null) {
                    runOnUiThread {
                        Toast.makeText(
                            this@MainActivity,
                            "播放失败:" + throwable.message,
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
                null
            }
        } else {
            if (!showFailTips) return
            runOnUiThread {
                Toast.makeText(
                    this@MainActivity,
                    "连接或打开摄像头失败",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    private fun stopPlay(showFailTips: Boolean) {
        val stopState = MjpegDecoderManager.stopVideoPlay(pixelType)
        if (stopState) {
            btn_play!!.setImageResource(R.drawable.ic_play)
            tv_tips!!.text = "已暂停"
            isPlay = false
            try {
                socket?.close()
                socket = null
                state = false
            } catch (e: Exception) {
                e.printStackTrace()
            }
        } else {
            if (showFailTips) {
                Toast.makeText(this@MainActivity, "暂停失败", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun selectPixelTv(tv: TextView?) {
        if (tv == null) return
        tvPixelList.forEachIndexed { index, textView ->
            textView?.isSelected = tv == textView
            if (textView?.isSelected == true) {
                pixelType = index
            }
        }
    }

    private fun selectDegreeTv(tv: TextView?) {
        if (tv == null) return
        tvDegreeList.forEachIndexed { index, textView ->
            textView?.isSelected = tv == textView
            if (textView?.isSelected == true) {
                MjpegDecoderManager.configRotationDegree(when (index) {
                    0 -> 0f
                    1 -> 90f
                    2 -> 180f
                    else -> 270f
                })
            }
        }
    }

    companion object {

        private val TAG = "MainActivity"

        private fun sendMsg(soc: Socket, messageData: ByteArray): Boolean {
            try {
                if (!soc.isClosed && !soc.isOutputShutdown && soc.isConnected) {
                    val os = soc.getOutputStream()
                    os.write(messageData) //写入完整数据包
                    os.flush()
                    Log.e(TAG,"发送成功:${ObjectUtil.bytes2Hex(messageData)}")
                    return true
                } else {
                    return false
                }
            } catch (e: IOException) {
                e.printStackTrace()
                return false
            }
        }
    }
}